package com.newland.esp.controller.intercepter;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.newland.esp.common.constant.RedisKeyConstant;
import com.newland.esp.common.util.DataResult;
import com.newland.esp.common.util.ThreadLocalUtils;
import com.newland.esp.common.util.login.Result;
import com.newland.esp.common.util.login.TokenUtil;
import com.newland.esp.entity.user.AdminEntity;
import com.newland.esp.service.user.SSOService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @param
 * @author lw
 * @descripe
 * @date 2021/8/17 9:19
 * @Version 1.0
 **/

public class CrosInterceptor implements HandlerInterceptor {
    private static Logger logger = LoggerFactory.getLogger(ManagerLoginInterceptor.class);

    @Autowired
    RedisTemplate<String,String> redisTemplate;

    @Autowired
    SSOService ssoService;

    // 请求处理的方法之前执行
    // 如果返回 true，执行下一个拦截器或目标程序，如果返回 false，不执行下一个拦截器或目标程序
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o) throws Exception {
        logger.info("====拦截到了方法：{}，CrosInterceptor 在该方法执行之前执行====");
        //在拦截器类解决跨域问题
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Authorization,userTicket,token");
        response.setHeader("Access-Control-Allow-Methods", "GET,HEAD,OPTIONS,POST,PUT,DELETE");
        response.setHeader("Access-Control-Allow-Credentials", "true");
        response.setHeader("Access-Control-Expose-Headers", "*");

        if (request.getMethod().equals("OPTIONS")){
            //跨域资源共享标准新增了一组 HTTP 首部字段，允许服务器声明哪些源站有权限访问哪些资源。
            // 另外，规范要求，对那些可能对服务器数据产生副作用的 HTTP 请求方法（特别是 GET 以外的 HTTP 请求，或者搭配某些 MIME 类型的 POST 请求），
            // 浏览器必须首先使用 OPTIONS 方法发起一个预检请求（preflight request），
            // 从而获知服务端是否允许该跨域请求。服务器确认允许之后，才发起实际的 HTTP 请求。
            // 在预检请求的返回中，服务器端也可以通知客户端，是否需要携带身份凭证（包括 Cookies 和 HTTP 认证相关数据）。
            // 参考：https://developer.mozilla.org/zh-CN/docs/Web/HTTP/Access_control_CORS
            response.setStatus(HttpServletResponse.SC_OK);
        }



        String token = TokenUtil.getRequestToken(request);
        //如果token为空
        if (StringUtils.isBlank(token)) {
            setReturn(response,300,"用户未登录，请先登录哦");
            return false;
        }

//        String s = redisTemplate.opsForValue().get(RedisKeyConstant.USER_TICKET + ":" + token);
//        if (!(token.equals(userTicket))){
//            setReturn(response,301,"用户未登录，请先登录呀");
//            return false;
//        }
        return true;

    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }

    //返回错误信息
    private static void setReturn(HttpServletResponse response, int code, String msg) throws IOException {
        HttpServletResponse httpResponse = (HttpServletResponse) response;

        //UTF-8编码
        httpResponse.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=utf-8");
        DataResult result = DataResult.getResult(code, msg);
        System.out.println(JSONObject.toJSONString(result));
        httpResponse.getWriter().print(JSONObject.toJSONString(result));
    }
}
